﻿using Microsoft.Extensions.DependencyInjection;

namespace dz.util.core
{

    public class HttpService
{
        private readonly IHttpClientFactory httpClientFactory;
        private static readonly Lazy<HttpService>instance = new Lazy<HttpService>(() => new HttpService());

        private HttpService()
        {
            // 创建服务集合
            ServiceCollection services = new ServiceCollection();
            services.AddHttpClient("DefaultClient")
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
            {
                MaxConnectionsPerServer = 256 // 根据需求调整
            })
            .SetHandlerLifetime(TimeSpan.FromMinutes(5)); // 适当延长生命周期


            // 构建服务提供者
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            // 获取HttpClientFactory实例
            httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
        }

        public IHttpClientFactory HttpClientFactory => httpClientFactory;

        public static HttpService Instance => instance.Value;
    }
}